package com.andova.camera

import android.os.Bundle
import android.view.SurfaceHolder
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.FaceNeuralNetwork
import com.andova.cameraview.CameraView
import com.andova.cameraview.Size
import com.andova.face.BaseFaceDetector
import com.andova.face.DetectorProxy
import com.andova.face.ICameraCheckListener
import com.andova.face.SystemFaceDetector
import com.andova.face.detector.CameraProvider
import com.andova.face.preview.CompatCameraPreview
import com.andova.opengles.databinding.AcCamera2Binding
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException

class Camera2Activity : AppCompatActivity() {
    private lateinit var mBinding: AcCamera2Binding
    private var mBackDetectorProxy: DetectorProxy? = null
    private var mFrontDetectorProxy: DetectorProxy? = null

    //    private val auth = "82F97B059B9FD4B792B1E46F72CC4880987826B0C0AC289A57F7BAC77C05702FF7E09FA772F4F1B900E85D7220C4F9F2142E13F71D36B1A7378576C78A6EA13EA0FFC96089ADC05DD6F304FC192ACE4E72B796E2565E34563976F11773D62D31556F8B4C7257ECE737FA4BE7DCD81DB4D99C35C117013E208A2C960D3C73ED5FF45FF4396F0A0139F8EA20AE85DECF9A142888E8ED1A29F75E500D7C05AE7FA8FE902984B353A0A11FF4BB66F72B16BE1975FC66E988A3A69934149B082403E4CCC00CAC8D2AB114604C0C89EACDCD77599E6A4D3D4BBAA71E9076FC9F4EE81FE591CCDD1C216500B08273C72A778B2623100FF318337EE36D749D75FA7B6BA9"
    private val auth = "FA3075E245143FAF68BF5601CE577EB42A5B8E12FE5A3EF6E48212B1B748E9AC01834C2DAA8D8F4C3B38041435DEEE19942F11B0F088E3678FB0A699583EF826A9CB29AEDE77347EA8A62E6A4699DCFADBF09CC8160FD023C37FA57805A9AA82F19F5A301C62D389032B36A97A699006FE396BED0B12A7012EC9DC108277CCA969C36EAF076A3A09A7D7D6CB5B227012C25970A379736C09366B8D9A7D75ABF1F99DB71C6E4D63EA7E075319190C93127BE43A1DF6368BE9F115B0D0050CA10D62DB41F455490C11E3DB22667595D44232E2574449B09FE7A50BB2B3078C1D7D40280E8870AF063DA6B6F1DD627A34EF1B0EBEA72B8D4FFD845E4766C05D0600"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (FaceNeuralNetwork.ActiveLibrary(this, auth) != 0) {
            Toast.makeText(this, "设备人脸识别库未激活", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        FaceNeuralNetwork.SetThreadCount(2)
        mBinding = AcCamera2Binding.inflate(layoutInflater)
        setContentView(mBinding.root)
//        initFrontCamera()
        initBackCamera()
    }

    private fun initBackCamera() {
        mBackDetectorProxy = DetectorProxy.Builder(CompatCameraPreview(mBinding.backcamera))
                .setFaceDetector(object : BaseFaceDetector() {
                    override fun detectionFaces(data: ByteArray?, camera: CameraProvider) {
                        data ?: return
                        decodeToOriginalBitmap(data, previewWidth, previewHeight)
                        return
                        val points = faceDetectPoint(data, previewWidth, previewHeight)
                        if (points == null) mBinding?.backcamera?.lazyCallback(1500L) else mBinding?.backcamera?.lazyCallback(-1L)
                    }
                })
                .setCheckListener(object : ICameraCheckListener {
                    override fun checkPermission(isAllow: Boolean) {}
                    override fun checkPixels(pixels: Long, isSupport: Boolean) {}
                    override fun checkPreviewSize(sizes: List<Size>?, holder: SurfaceHolder?): Size? {
                        for (s in sizes ?: return null) {
                            if (s.width == 720 && s.height == 1080) return s
                        }
                        return null
                    }

                    override fun checkPictureSize(sizes: List<Size>?, holder: SurfaceHolder?): Size? {
                        for (s in sizes ?: return null) {
                            if (s.width == 720 && s.height == 1080) return s
                        }
                        return null
                    }
                })
                .setDisplayOrientation(0)
                .setCameraId(CameraView.FACING_BACK)
                .build()
    }

    private fun initFrontCamera() {
        mFrontDetectorProxy = DetectorProxy.Builder(CompatCameraPreview(mBinding?.frontcamera!!))
                .setFaceDetector(SystemFaceDetector())
                .setDisplayOrientation(0)
                .setFaceDetector(object : BaseFaceDetector() {
                    override fun detectionFaces(data: ByteArray?, camera: CameraProvider) {
                        faceDetectPoint(data ?: return, previewWidth, previewHeight)
                    }
                })
                .setMinCameraPixels(1000000)
                .setCameraId(CameraView.FACING_FRONT)
                .build()
    }

    private val gson = Gson()
    private fun faceDetectPoint(bytes: ByteArray, w: Int, h: Int): FloatArray? {
        val dataBean = facePoint(bytes, w, h) ?: return null
        dataBean.data?.apply { if (size <= 0) return null } ?: return null
        var maxData = dataBean.data[0] ?: return null
        for (data in dataBean.data ?: return null) {
            if (data.area <= maxData.area) continue
            maxData = data
        }
        try {
            val yaw = maxData.yaw.toFloat()
        } catch (e: NumberFormatException) {
        }
        val points = maxData.point
        val pointArray = FloatArray(points.size)
        for (i in points.indices) pointArray[i] = points[i].toFloat()
        return pointArray
    }

    private fun facePoint(bytes: ByteArray, w: Int, h: Int): FaceDTO? {
        val sss: String
        try {
            sss = FaceNeuralNetwork.FaceDetect(
                    bytes, w * h * 3 / 2, w, h,
                    FaceNeuralNetwork.ImageYuv420SP, 90
            )
        } catch (ignore: Exception) {
            return null
        }
        if (sss?.length ?: 0 < 20) return null
        val pointBean: FaceDTO
        try {
            pointBean = gson.fromJson(sss, FaceDTO::class.java)
        } catch (ignore: JsonSyntaxException) {
            return null
        }
        return pointBean
    }

    override fun onResume() {
        super.onResume()
        mBackDetectorProxy?.detector(true)
//        mFrontDetectorProxy?.detector(true, true, 3)
    }

    override fun onPause() {
        super.onPause()
        mBackDetectorProxy?.release()
        mFrontDetectorProxy?.release()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (!hasFocus) return
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }
}